<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next';
import {
  getUserListByPage,
  editUser,
  deleteUser,
  addUser,
  batchDeleteUsers
} from '@/api/user/index';
import type { UserPageParam, UserVO, UserEditParam, UserAddParam, UserDeleteByIdsParam } from '@/api/user/types';

// 性别、状态枚举
const GENDER_OPTIONS = [
  { label: '全部', value: undefined },
  { label: '男', value: 1 },
  { label: '女', value: 2 },
];
const STATUS_OPTIONS = [
  { label: '全部', value: undefined },
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 },
];

// 分页参数
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 查询表单数据
const searchForm = ref<UserPageParam>({
  username: '',
  phone: '',
  gender: undefined,
  status: undefined,
  pageNum: 1,
  pageSize: 10,
});

// 表格数据
const tableData = ref<UserVO[]>([]);
const loading = ref(false);

const columns = [
  { colKey: 'row-select',type: 'multiple',width: 50 },
  { colKey: 'index',title: '序号',width: 80, },
  { colKey: 'username', title: '用户名', align: 'center', ellipsis: true },
  { colKey: 'realName', title: '昵称', align: 'center', ellipsis: true },
  { colKey: 'email', title: '邮箱', align: 'center', ellipsis: true },
  { colKey: 'phone', title: '手机号', align: 'center', ellipsis: true },
  { colKey: 'gender', title: '性别', align: 'center', ellipsis: true, width: 70 },
  { colKey: 'status', title: '状态', align: 'center', ellipsis: true, width: 80 },
  { colKey: 'createTime', title: '创建时间', align: 'center', width: 180 },
  { colKey: 'updateTime', title: '更新时间', align: 'center', width: 180 },
  { colKey: 'actions', title: '操作', align: 'center', width: 120, fixed: 'right' },
];

const selectedRowKeys = ref([]);

// 编辑弹窗相关
const editVisible = ref(false);
const editLoading = ref(false);
const editForm = ref<UserEditParam>({
  id: 0,
  username: '',
  realName: '',
  email: '',
  phone: '',
  gender: 1,
  status: 1,
});

const editRules = {
  username: [{ required: true, message: '请输入用户名', type: 'error' }],
  realName: [{ required: true, message: '请输入昵称', type: 'error' }],
  email: [
    { required: true, message: '请输入邮箱', type: 'error' },
    { pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, message: '邮箱格式不正确', type: 'error' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', type: 'error' }
  ],
  gender: [{ required: true, message: '请选择性别', type: 'error' }],
  status: [{ required: true, message: '请选择状态', type: 'error' }],
};

// 新增弹窗相关
const addVisible = ref(false);
const addLoading = ref(false);
const addForm = ref<UserAddParam>({
  username: '',
  password: '',
  email: '',
  realName: '',
  phone: '',
  gender: 1,
  status: 1,
});

const addRules = {
  username: [
    { required: true, message: '请输入用户名', type: 'error' },
    { min: 3, max: 20, message: '用户名3-20位', type: 'error' }
  ],
  password: [
    { required: true, message: '请输入密码', type: 'error' },
    { min: 6, message: '密码至少6位', type: 'error' }
  ],
  email: [
    { pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, message: '邮箱格式不正确', type: 'error' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', type: 'error' }
  ],
  gender: [{ required: true, message: '请选择性别', type: 'error' }],
  status: [{ required: true, message: '请选择状态', type: 'error' }],
};

/**
 * 查询用户列表
 */
const fetchUserList = async () => {
  loading.value = true;
  try {
    const params = { ...searchForm.value, pageNum: pageNum.value, pageSize: pageSize.value, orderBy: 'update_time desc' };
    console.log('[用户列表查询参数]', params);
    const res = await getUserListByPage(params);
    console.log('用户列表接口返回', res.data);
    if (res.data && res.data.code === 200) {
      tableData.value = res.data.data.list;
      total.value = res.data.data.total;
      // 同步后端返回的分页信息
      pageNum.value = res.data.data.pageNum;
      pageSize.value = res.data.data.pageSize;
      console.log('表格数据', tableData.value);
      selectedRowKeys.value = [];
    } else {
      await MessagePlugin.error(res.data?.message || '获取用户列表失败');
    }
  } catch (error) {
    await MessagePlugin.error('获取用户列表异常');
    console.error('[用户列表异常]', error);
  } finally {
    loading.value = false;
  }
};

/**
 * 重置查询表单
 */
const resetForm = () => {
  searchForm.value = { username: '', phone: '', gender: undefined, status: undefined, pageNum: 1, pageSize: 10 };
  pageNum.value = 1;
  selectedRowKeys.value = [];
  fetchUserList();
};

const handleEdit = (row: UserVO) => {
  // 回显数据
  editForm.value = {
    id: row.id,
    username: row.username,
    realName: row.realName,
    email: row.email,
    phone: row.phone,
    gender: row.gender,
    status: row.status,
  };
  editVisible.value = true;
};

const handleEditSubmit = async () => {
  editLoading.value = true;
  try {
    const res = await editUser(editForm.value);
    if (res.data && res.data.code === 200) {
      await MessagePlugin.success('编辑成功');
      editVisible.value = false;
      await fetchUserList();
    } else {
      await MessagePlugin.error(res.data?.message || '编辑失败');
    }
  } catch (e) {
    await MessagePlugin.error('编辑异常');
  } finally {
    editLoading.value = false;
  }
};

const handleDelete = (row: UserVO) => {
  const dialog = DialogPlugin.confirm({
    header: '确认删除',
    body: `确定要删除用户「${row.username}」吗？`,
    onConfirm: async () => {
      try {
        const res = await deleteUser(row.username);
        if (res.data && res.data.code === 200) {
          await MessagePlugin.success('删除成功');
          dialog.hide();
          await fetchUserList();
        } else {
          await MessagePlugin.error(res.data?.message || '删除失败');
        }
      } catch (e) {
        await MessagePlugin.error('删除异常');
      }
    },
  });
};

const handleAdd = () => {
  addForm.value = {
    username: '',
    password: '',
    email: '',
    realName: '',
    phone: '',
    gender: 1,
    status: 1,
  };
  addVisible.value = true;
};

const handleAddSubmit = async () => {
  addLoading.value = true;
  try {
    const res = await addUser(addForm.value);
    if (res.data && res.data.code === 200) {
      await MessagePlugin.success('新增成功');
      addVisible.value = false;
      await fetchUserList();
    } else {
      await MessagePlugin.error(res.data?.message || '新增失败');
    }
  } catch (e) {
    await MessagePlugin.error('新增异常');
  } finally {
    addLoading.value = false;
  }
};

const sortedTableData = computed(() => {
  // 确保 tableData.value 是数组
  if (!Array.isArray(tableData.value)) {
    return [];
  }
  
  return [...tableData.value].sort((a, b) => {
    const t1 = new Date(a.createTime).getTime();
    const t2 = new Date(b.createTime).getTime();
    return t2 - t1;
  });
});

const handleSelectAll = (keys: (string | number)[]) => {
  selectedRowKeys.value = keys;
};

const handleSelectChange = (keys: (string | number)[]) => {
  selectedRowKeys.value = keys;
};

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    MessagePlugin.warning('请选择要删除的用户');
    return;
  }
  
  const dialog = DialogPlugin.confirm({
    header: '确认删除',
    body: `确定要删除这 ${selectedRowKeys.value.length} 个用户吗？`,
    onConfirm: async () => {
      try {
        // 获取选中的用户ID
        const selectedIds = selectedRowKeys.value as number[];
        
        // 确保 tableData.value 是数组
        if (!Array.isArray(tableData.value)) {
          await MessagePlugin.error('数据异常，请刷新页面重试');
          return;
        }
        
        // 调用批量删除接口
        const res = await batchDeleteUsers(selectedIds);
        if (res.data && res.data.code === 200) {
          await MessagePlugin.success(`成功删除 ${selectedIds.length} 个用户`);
          selectedRowKeys.value = [];
          dialog.hide();
          await fetchUserList();
        } else {
          await MessagePlugin.error(res.data?.message || '批量删除失败');
        }
      } catch (error) {
        console.error('批量删除失败:', error);
        await MessagePlugin.error('批量删除失败，请检查网络连接');
      }
    },
  });
};

// 分页变化处理
const handlePageChange = () => {
  // 清除选择状态
  selectedRowKeys.value = [];
  fetchUserList();
};

// 用户状态切换
const handleStatusChange = async (row: UserVO, val: boolean) => {
  const newStatus = val ? 1 : 0;
  if (row.status === newStatus) return;
  const oldStatus = row.status;
  row.status = newStatus;
  try {
    const res = await editUser({ ...row, status: newStatus });
    if (res.data && res.data.code === 200) {
      await fetchUserList();
    } else {
      row.status = oldStatus;
    }
  } catch (e) {
    row.status = oldStatus;
  }
};

onMounted(() => {
  fetchUserList();
});
</script>

<template>
  <t-card class="user-list-card" bordered>
    <div class="search-form">
      <t-form layout="inline" :data="searchForm" label-width="auto">
        <t-form-item label="用户名" name="username">
          <t-input v-debounce.input v-model="searchForm.username" placeholder="请输入用户名" clearable style="width: 200px;" />
        </t-form-item>
        <t-form-item label="手机号" name="phone">
          <t-input v-debounce.input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </t-form-item>
        <t-form-item label="性别" name="gender">
          <t-select v-model="searchForm.gender" :options="GENDER_OPTIONS" placeholder="请选择性别" clearable />
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-select v-model="searchForm.status" :options="STATUS_OPTIONS" placeholder="请选择状态" clearable />
        </t-form-item>
      </t-form>
    </div>
    <div style="display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 12px;">
      <div>
        <t-button theme="primary" v-throttle="fetchUserList">查询</t-button>
        <t-button v-throttle="resetForm" style="margin-left: 8px;">重置</t-button>
      </div>
      <div style="display: flex; gap: 8px; align-items: center;">
        <span v-if="selectedRowKeys.length > 0" style="color: #666; font-size: 14px;">
          已选择 {{ selectedRowKeys.length }} 项
        </span>
        <t-button theme="danger" :disabled="!selectedRowKeys.length" v-throttle="handleBatchDelete">批量删除</t-button>
        <t-button theme="primary" v-throttle="handleAdd">新增</t-button>
      </div>
    </div>
    <t-table
      row-key="id"
      :data="sortedTableData"
      :loading="loading"
      :columns="columns"
      hover
      size="medium"
      class="user-table"
      ellipsis
      :selected-row-keys="selectedRowKeys"
      @select-all="handleSelectAll"
      @select-change="handleSelectChange"
    >
      <template #index="{ rowIndex }">
        {{ typeof rowIndex === 'number' ? rowIndex + 1 + (pageNum - 1) * pageSize : '-' }}
      </template>
      <template #username="{ row }">
        {{ row && row.username != null ? row.username : '-' }}
      </template>
      <template #realName="{ row }">
        {{ row && row.realName != null ? row.realName : '-' }}
      </template>
      <template #email="{ row }">
        {{ row && row.email != null ? row.email : '-' }}
      </template>
      <template #phone="{ row }">
        {{ row && row.phone != null ? row.phone : '-' }}
      </template>
      <template #gender="{ row }">
        {{ (!row || row.gender == null) ? '-' : (row.gender === 1 ? '男' : row.gender === 2 ? '女' : '-') }}
      </template>
      <template #status="{ row, rowIndex }">
        <t-switch
          v-if="row"
          :model-value="row.status === 1"
          disabled
        />
        <span v-else>-</span>
      </template>
      <template #createTime="{ row }">
        {{ row && row.createTime != null ? row.createTime : '-' }}
      </template>
      <template #updateTime="{ row }">
        {{ row && row.updateTime != null ? row.updateTime : '-' }}
      </template>
      <template #empty>
        <div style="padding: 32px 0; color: #999; text-align: center;">暂无数据，请调整查询条件</div>
      </template>
      <template #actions="{ row }">
        <div style="display: flex; gap: 8px; align-items: center;">
          <t-button theme="primary" size="small" variant="outline" v-throttle="()=>handleEdit(row)">编辑</t-button>
          <t-button theme="danger" size="small" variant="outline" v-throttle="()=>handleDelete(row)">删除</t-button>
        </div>
      </template>
    </t-table>
    <div class="pagination-wrapper">
      <t-pagination
        v-model:current="pageNum"
        v-model:page-size="pageSize"
        :total="total"
        :page-size-options="[10, 20, 50, 100]"
        show-jumper
        show-total
        @change="handlePageChange"
      />
    </div>
  </t-card>
  <t-dialog v-model:visible="editVisible" header="编辑用户" :confirm-btn="{ content: '保存', loading: editLoading }" cancel-btn="取消" @confirm="handleEditSubmit">
    <t-form :data="editForm" :rules="editRules" label-align="right" layout="vertical">
      <t-form-item label="用户名" name="username">
        <t-input v-debounce.input v-model="editForm.username" placeholder="请输入用户名" disabled />
      </t-form-item>
      <t-form-item label="昵称" name="realName">
        <t-input v-debounce.input v-model="editForm.realName" placeholder="请输入昵称" />
      </t-form-item>
      <t-form-item label="邮箱" name="email">
        <t-input v-debounce.input v-model="editForm.email" placeholder="请输入邮箱" disabled />
      </t-form-item>
      <t-form-item label="手机号" name="phone">
        <t-input v-debounce.input v-model="editForm.phone" placeholder="请输入手机号" />
      </t-form-item>
      <t-form-item label="性别" name="gender">
        <t-select v-model="editForm.gender" :options="GENDER_OPTIONS.filter(opt => opt.value !== undefined)" placeholder="请选择性别" />
      </t-form-item>
      <t-form-item label="状态" name="status">
        <t-select v-model="editForm.status" :options="STATUS_OPTIONS.filter(opt => opt.value !== undefined)" placeholder="请选择状态" />
      </t-form-item>
    </t-form>
  </t-dialog>
  <t-dialog v-model:visible="addVisible" header="新增用户" :confirm-btn="{ content: '保存', loading: addLoading }" cancel-btn="取消" @confirm="handleAddSubmit">
    <t-form :data="addForm" :rules="addRules" label-align="right" layout="vertical">
      <t-form-item label="用户名" name="username">
        <t-input v-debounce.input v-model="addForm.username" placeholder="请输入用户名" />
      </t-form-item>
      <t-form-item label="密码" name="password">
        <t-input v-debounce.input v-model="addForm.password" type="password" placeholder="请输入密码" />
      </t-form-item>
      <t-form-item label="昵称" name="realName">
        <t-input v-debounce.input v-model="addForm.realName" placeholder="请输入昵称" />
      </t-form-item>
      <t-form-item label="邮箱" name="email">
        <t-input v-debounce.input v-model="addForm.email" placeholder="请输入邮箱" />
      </t-form-item>
      <t-form-item label="手机号" name="phone">
        <t-input v-debounce.input v-model="addForm.phone" placeholder="请输入手机号" />
      </t-form-item>
      <t-form-item label="性别" name="gender">
        <t-select v-model="addForm.gender" :options="GENDER_OPTIONS.filter(opt => opt.value !== undefined)" placeholder="请选择性别" />
      </t-form-item>
      <t-form-item label="状态" name="status">
        <t-select v-model="addForm.status" :options="STATUS_OPTIONS.filter(opt => opt.value !== undefined)" placeholder="请选择状态" />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<style lang="less" scoped>
.user-list-card {
  background: var(--td-bg-color-container, #fff);
  margin: 24px 8px;
  padding: 24px;
}
.search-form {
  margin-bottom: 16px;
}
.user-table {
  margin-bottom: 16px;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>